<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="openDialog"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="isLoading" :data="list">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- layout 分页的样式（功能） -->
            <!-- current-page  当前的页码 -->
            <!-- page-sizes 设置当前的页容量 第一个一般是和page-size页容量保持一致-->
            <!-- page-size  当前的页容量 -->
            <!-- total 一共多少条数据 -->
            <!-- size-change 改变页容量 触发 -->
            <!-- current-change 当前页码变化的时候触发 -->
            <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pagesize"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfo.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfo.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyInfo.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="title" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAddRole">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        :close-on-click-modal="false"
        @close="closeAssignDialog"
        @open="getPermissionList"
      >
        <!-- show-checkbox 展示树状的复选框
         :check-strictly：让父子不关联 -->
        <el-tree ref="tree" v-loading="treeLoading" :data="permissionList" node-key="id" :props="{label:'name'}" show-checkbox :check-strictly="true" default-expand-all="" />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="confirmAssign">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import { getRoleListApi, delRoleApi, addRoleApi, getRoleDetailApi, editRoleApi, assignPermissionApi } from '@/api/setting'
import { getPermissionListApi } from '@/api/permission'
import { getCompanyApi } from '@/api/company'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pagesize: 10,
      list: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不可为空', trigger: 'blur' }
        ]
      },
      companyInfo: {},
      // 控制弹框的隐藏和展示
      showAssignDialog: false,
      // 点击时的角色id
      roleId: '',
      permissionList: [],
      // 树状结构的加载中
      treeLoading: false
    }
  },
  computed: {
    title() {
      if (this.form.id) {
        return '编辑角色'
      } else {
        return '添加角色'
      }
    }
  },
  created() {
    this.getRoleList()
    this.getCompany()
  },
  methods: {
    // 1.确定按钮绑定事件
    // 2.封装分配权限的接口
    // 3.获取树状结构中勾选的数据 this.$refs.tree.getCheckedKeys()
    // 4.调用接口
    // 5.提示+关闭弹框
    async confirmAssign() {
      // 获取勾选的id
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPermissionApi({
        id: this.roleId,
        permIds
      })
      this.$message.success('恭喜，分配权限成功')
      this.closeAssignDialog()
    },
    /**
     * 获取权限列表
     */
    async getPermissionList() {
      this.treeLoading = true
      const { data } = await getPermissionListApi()
      this.permissionList = transListToTreeData(data, '0')
      // 获取回显数据
      const { data: { permIds }} = await getRoleDetailApi(this.roleId)
      // 进行回显操作，通过id回显 需要给el-tree 配置node-key
      this.$refs.tree.setCheckedKeys(permIds)
      this.treeLoading = false
    },
    /**
     * 添加权限
     */
    assignPermission(id) {
      this.showAssignDialog = true
      this.roleId = id
    },
    /**
     * 控制分配权限弹框的隐藏
     */
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getCompany() {
      const companyId = this.$store.state.user.userInfo.companyId
      const res = await getCompanyApi(companyId)
      this.companyInfo = res.data
    },
    /**
     * 编辑角色
     */
    async editRole(id) {
      this.showDialog = true
      const res = await getRoleDetailApi(id)
      this.form = res.data
    },
    /**
     * 添加角色
     */
    confirmAddRole() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          // 编辑状态
          await editRoleApi(this.form)
          this.$message.success('恭喜！修改成功')
        } else {
          // 添加状态
          await addRoleApi(this.form)
          this.$message.success('恭喜！添加成功')
        }
        this.closeDialog()
        this.getRoleList()
      })
    },
    openDialog() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    /**
     * 删除
     */
    delRole(id) {
      // console.log(id)
      this.$confirm('您确定要删除吗', '温馨提示')
        .then(async() => {
          await delRoleApi(id)
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {})
    },
    indexMethod(row) {
      // 当前页之前 所有的数据总和 + row +1
      return (this.page - 1) * this.pagesize + row + 1
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 一旦切换页容量 就把当前页重置为1
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    async getRoleList() {
      this.isLoading = true
      const res = await getRoleListApi(this.page, this.pagesize)
      this.list = res.data.rows
      this.total = res.data.total
      this.isLoading = false
    }
  }
}
</script>
<style scoped lang="scss">
</style>
